﻿/// Write a program that reads a list of words from a file words.txt and finds how many times each of the words
/// is contained in another file test.txt. The result should be written in the file result.txt
/// and the words should be sorted by the number of their occurrences in descending order.
/// Handle all possible exceptions in your methods.



// Regex.Matches(str, ">(.*?)<")
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Security;
using System.Collections.Generic;
using System.Linq;


namespace c_sh_II_lek_6_files
{
    class zad13
    {
        static void Main()
        {
            string words = @"..\..\words.txt";
            string result = @"..\..\result.txt";
            string test = @"..\..\test.txt";
            
            string regex = @"\b(" + String.Join("|", File.ReadAllLines(words)) + @")\b";
            Dictionary<string, int> dic = new Dictionary<string, int>();

            using (StreamReader _in = new StreamReader(test))
            {

                    string line = _in.ReadLine();
                    while (line != null)
                    {
                        MatchCollection matchText = Regex.Matches(line, regex);
                        foreach (Match match in matchText)
                        {
                            string temp = match.ToString();

                            if (dic.ContainsKey(temp))
                            {
                                dic[temp]++;
                            }
                            else
                            {
                                dic.Add(temp,1);
                            }
                            
                        }
                        
                        line = _in.ReadLine();
                    }

                    var items = from pair in dic
                            orderby pair.Value descending
                            select pair;

                    using (StreamWriter _out = new StreamWriter(result))
                    {
                        foreach (var element in items)
                        {
                            _out.WriteLine(element.Key);
                            Console.WriteLine(element);
                        }
                    }

            }

            //File.Delete(input);
            //File.Copy(output, input);
            //File.Delete(output);
        }
    }
}
